<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>JVM系列-第11章-垃圾回收相关概念 | 风祈的时光录</title><meta name="keywords" content="JVM，虚拟机。"><meta name="author" content="youthlql"><meta name="copyright" content="youthlql"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="JVM系列-第11章-垃圾回收相关概念。">
<meta property="og:type" content="article">
<meta property="og:title" content="JVM系列-第11章-垃圾回收相关概念">
<meta property="og:url" content="https://imlql.cn/post/4d401a8b.html">
<meta property="og:site_name" content="风祈的时光录">
<meta property="og:description" content="JVM系列-第11章-垃圾回收相关概念。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://upyunimg.imlql.cn/lql_static@latest/logo/jvm.png">
<meta property="article:published_time" content="2020-11-17T04:33:24.000Z">
<meta property="article:modified_time" content="2022-07-24T11:02:09.800Z">
<meta property="article:author" content="youthlql">
<meta property="article:tag" content="JVM">
<meta property="article:tag" content="虚拟机">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://upyunimg.imlql.cn/lql_static@latest/logo/jvm.png"><link rel="shortcut icon" href="https://npm.elemecdn.com/youthlql@1.0.8/blog/favicon.png"><link rel="canonical" href="https://imlql.cn/post/4d401a8b"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//hm.baidu.com"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://npm.elemecdn.com/@fortawesome/fontawesome-free@6/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://npm.elemecdn.com/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?f693ff99cc7e613b88cf5b729a14b48b";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();
</script><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery@2/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'JVM系列-第11章-垃圾回收相关概念',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-07-24 19:02:09'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="https://npm.elemecdn.com/lql_static@latest/butterfly_static/css/ali_icon.css"><link rel="stylesheet" href="https://npm.elemecdn.com/lql_static@latest/butterfly_static/css/2-24-mogai.css"><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="风祈的时光录" type="application/atom+xml">
</head><body><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/avatar/2.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/archives/"><div class="headline">文章</div><div class="length-num">37</div></a></div><div class="data-item"><a href="/tags/"><div class="headline">标签</div><div class="length-num">21</div></a></div><div class="data-item"><a href="/categories/"><div class="headline">分类</div><div class="length-num">13</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://upyunimg.imlql.cn/lql_static@latest/logo/jvm.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">风祈的时光录</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw iconfont icon-shouyex"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw iconfont icon-zuixinwenzhang_huaban"></i><span> 找文章</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/categories/"><i class="fa-fw iconfont icon-fenlei1"></i><span> 分类</span></a></li><li><a class="site-page child" href="/tags/"><i class="fa-fw iconfont icon-biaoqian1"></i><span> 标签</span></a></li><li><a class="site-page child" href="/archives/"><i class="fa-fw iconfont icon-shijianzhou"></i><span> 归档</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">JVM系列-第11章-垃圾回收相关概念</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2020-11-17T04:33:24.000Z" title="发表于 2020-11-17 12:33:24">2020-11-17</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-07-24T11:02:09.800Z" title="更新于 2022-07-24 19:02:09">2022-07-24</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/JVM/">JVM</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/JVM/1-%E5%86%85%E5%AD%98%E4%B8%8E%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E7%AF%87/">1.内存与垃圾回收篇</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">10.5k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>36分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="垃圾回收相关概念"><a href="#垃圾回收相关概念" class="headerlink" title="垃圾回收相关概念"></a>垃圾回收相关概念</h1><h2 id="System-gc-的理解"><a href="#System-gc-的理解" class="headerlink" title="System.gc() 的理解"></a>System.gc() 的理解</h2><ol>
<li>在默认情况下，通过System.gc()者Runtime.getRuntime().gc() 的调用，<strong>会显式触发Full GC</strong>，同时对老年代和新生代进行回收，尝试释放被丢弃对象占用的内存。</li>
<li>然而System.gc()调用附带一个免责声明，无法保证对垃圾收集器的调用(不能确保立即生效)</li>
<li>JVM实现者可以通过System.gc() 调用来决定JVM的GC行为。而一般情况下，垃圾回收应该是自动进行的，<strong>无须手动触发，否则就太过于麻烦了。</strong>在一些特殊情况下，如我们正在编写一个性能基准，我们可以在运行之间调用System.gc()</li>
</ol>
<p><strong>代码示例：手动执行 GC 操作</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SystemGCTest</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">new</span> SystemGCTest();</span><br><span class="line">        System.gc();<span class="comment">//提醒jvm的垃圾回收器执行gc,但是不确定是否马上执行gc</span></span><br><span class="line">        <span class="comment">//与Runtime.getRuntime().gc();的作用一样。</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//        System.runFinalization();//强制调用使用引用的对象的finalize()方法</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//如果发生了GC，这个finalize()一定会被调用</span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">finalize</span><span class="params">()</span> <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.finalize();</span><br><span class="line">        System.out.println(<span class="string">&quot;SystemGCTest 重写了finalize()&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出结果不确定：有时候会调用 finalize() 方法，有时候并不会调用</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">SystemGCTest 重写了finalize()</span><br><span class="line">或</span><br><span class="line">空</span><br></pre></td></tr></table></figure>





<h3 id="手动-GC-理解不可达对象的回收行为"><a href="#手动-GC-理解不可达对象的回收行为" class="headerlink" title="手动 GC 理解不可达对象的回收行为"></a>手动 GC 理解不可达对象的回收行为</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//加上参数：  -XX:+PrintGCDetails</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">LocalVarGC</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">localvarGC1</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">byte</span>[] buffer = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">10</span> * <span class="number">1024</span> * <span class="number">1024</span>];<span class="comment">//10MB</span></span><br><span class="line">        System.gc();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">localvarGC2</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">byte</span>[] buffer = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">10</span> * <span class="number">1024</span> * <span class="number">1024</span>];</span><br><span class="line">        buffer = <span class="keyword">null</span>;</span><br><span class="line">        System.gc();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">localvarGC3</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">byte</span>[] buffer = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">10</span> * <span class="number">1024</span> * <span class="number">1024</span>];</span><br><span class="line">        &#125;</span><br><span class="line">        System.gc();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">localvarGC4</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        &#123;</span><br><span class="line">            <span class="keyword">byte</span>[] buffer = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">10</span> * <span class="number">1024</span> * <span class="number">1024</span>];</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">int</span> value = <span class="number">10</span>;</span><br><span class="line">        System.gc();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">localvarGC5</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        localvarGC1();</span><br><span class="line">        System.gc();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        LocalVarGC local = <span class="keyword">new</span> LocalVarGC();</span><br><span class="line">        <span class="comment">//通过在main方法调用这几个方法进行测试</span></span><br><span class="line">        local.localvarGC1();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>JVM参数：</p>
<p><code>-Xms256m -Xmx256m -XX:+PrintGCDetails -XX:PretenureSizeThreshold=15m</code></p>
<p>1、第四个参数是设置大对象直接进入老年代的阈值，由于我的电脑8G和视频里老师的电脑16G不太一样。我测试的时候10M的数组都是直接进入到了老年代，为了保持一样的效果，我同时设置了堆内存和大对象阈值，尽量和宋红康老师保持一致</p>
<p>2、我也查过了大对象阈值的默认值</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_011/0001.png">

<p>我不太懂这个默认值为啥是0，我猜测可能是代表什么比例，目前也没有搜到相关的东西。这个不太重要，暂时就没有太深究，希望读者有知道的可以告知我一声。</p>
<blockquote>
<p>看不懂GC日志请看笔者的  <strong>堆</strong>那篇文章</p>
</blockquote>
<p><strong>1、调用 localvarGC1() 方法</strong></p>
<p>执行 System.gc() 仅仅是将年轻代的 buffer 数组对象放到了老年代，buffer对象仍然没有回收</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">[GC (System.gc()) [PSYoungGen: 15492K-&gt;10728K(76288K)] 15492K-&gt;11000K(251392K), <span class="number">0.0066473</span> secs] [Times: user=<span class="number">0.08</span> sys=<span class="number">0.02</span>, real=<span class="number">0.01</span> secs] </span><br><span class="line">[<span class="function">Full <span class="title">GC</span> <span class="params">(System.gc()</span>) [PSYoungGen: 10728K-&gt;0<span class="title">K</span><span class="params">(76288K)</span>] [ParOldGen: 272K-&gt;10911<span class="title">K</span><span class="params">(175104K)</span>] 11000K-&gt;10911<span class="title">K</span><span class="params">(251392K)</span>, [Metaspace: 3492K-&gt;3492<span class="title">K</span><span class="params">(1056768K)</span>], 0.0097940 secs] [Times: user</span>=<span class="number">0.00</span> sys=<span class="number">0.00</span>, real=<span class="number">0.01</span> secs] </span><br><span class="line">Heap</span><br><span class="line"> PSYoungGen      total 76288K, used 655K [<span class="number">0x00000000fab00000</span>, <span class="number">0x0000000100000000</span>, <span class="number">0x0000000100000000</span>)</span><br><span class="line">  eden space 65536K, <span class="number">1</span>% used [<span class="number">0x00000000fab00000</span>,<span class="number">0x00000000faba3ee8</span>,<span class="number">0x00000000feb00000</span>)</span><br><span class="line">  from space 10752K, <span class="number">0</span>% used [<span class="number">0x00000000feb00000</span>,<span class="number">0x00000000feb00000</span>,<span class="number">0x00000000ff580000</span>)</span><br><span class="line">  to   space 10752K, <span class="number">0</span>% used [<span class="number">0x00000000ff580000</span>,<span class="number">0x00000000ff580000</span>,<span class="number">0x0000000100000000</span>)</span><br><span class="line"> ParOldGen       total 175104K, used 10911K [<span class="number">0x00000000f0000000</span>, <span class="number">0x00000000fab00000</span>, <span class="number">0x00000000fab00000</span>)</span><br><span class="line">  object space 175104K, <span class="number">6</span>% used [<span class="number">0x00000000f0000000</span>,<span class="number">0x00000000f0aa7d08</span>,<span class="number">0x00000000fab00000</span>)</span><br><span class="line"> Metaspace       used 3498K, capacity 4498K, committed 4864K, reserved 1056768K</span><br><span class="line">  <span class="class"><span class="keyword">class</span> <span class="title">space</span>    <span class="title">used</span> 387<span class="title">K</span>, <span class="title">capacity</span> 390<span class="title">K</span>, <span class="title">committed</span> 512<span class="title">K</span>, <span class="title">reserved</span> 1048576<span class="title">K</span></span></span><br></pre></td></tr></table></figure>



<p><strong>2、调用 localvarGC2() 方法</strong></p>
<p>由于 buffer 数组对象没有引用指向它，执行 System.gc() 将被回收</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">[GC (System.gc()) [PSYoungGen: 15492K-&gt;808K(76288K)] 15492K-&gt;816K(251392K), <span class="number">0.0294475</span> secs] [Times: user=<span class="number">0.00</span> sys=<span class="number">0.00</span>, real=<span class="number">0.04</span> secs] </span><br><span class="line">[<span class="function">Full <span class="title">GC</span> <span class="params">(System.gc()</span>) [PSYoungGen: 808K-&gt;0<span class="title">K</span><span class="params">(76288K)</span>] [ParOldGen: 8K-&gt;640<span class="title">K</span><span class="params">(175104K)</span>] 816K-&gt;640<span class="title">K</span><span class="params">(251392K)</span>, [Metaspace: 3385K-&gt;3385<span class="title">K</span><span class="params">(1056768K)</span>], 0.0054210 secs] [Times: user</span>=<span class="number">0.00</span> sys=<span class="number">0.00</span>, real=<span class="number">0.01</span> secs] </span><br><span class="line">Heap</span><br><span class="line"> PSYoungGen      total 76288K, used 1966K [<span class="number">0x00000000fab00000</span>, <span class="number">0x0000000100000000</span>, <span class="number">0x0000000100000000</span>)</span><br><span class="line">  eden space 65536K, <span class="number">3</span>% used [<span class="number">0x00000000fab00000</span>,<span class="number">0x00000000faceb9e0</span>,<span class="number">0x00000000feb00000</span>)</span><br><span class="line">  from space 10752K, <span class="number">0</span>% used [<span class="number">0x00000000feb00000</span>,<span class="number">0x00000000feb00000</span>,<span class="number">0x00000000ff580000</span>)</span><br><span class="line">  to   space 10752K, <span class="number">0</span>% used [<span class="number">0x00000000ff580000</span>,<span class="number">0x00000000ff580000</span>,<span class="number">0x0000000100000000</span>)</span><br><span class="line"> ParOldGen       total 175104K, used 640K [<span class="number">0x00000000f0000000</span>, <span class="number">0x00000000fab00000</span>, <span class="number">0x00000000fab00000</span>)</span><br><span class="line">  object space 175104K, <span class="number">0</span>% used [<span class="number">0x00000000f0000000</span>,<span class="number">0x00000000f00a01a8</span>,<span class="number">0x00000000fab00000</span>)</span><br><span class="line"> Metaspace       used 3392K, capacity 4496K, committed 4864K, reserved 1056768K</span><br><span class="line">  <span class="class"><span class="keyword">class</span> <span class="title">space</span>    <span class="title">used</span> 379<span class="title">K</span>, <span class="title">capacity</span> 388<span class="title">K</span>, <span class="title">committed</span> 512<span class="title">K</span>, <span class="title">reserved</span> 1048576<span class="title">K</span></span></span><br></pre></td></tr></table></figure>



<p><strong>3、调用 localvarGC3() 方法</strong></p>
<p>虽然出了代码块的作用域，但是 buffer 数组对象并没有被回收</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">[GC (System.gc()) [PSYoungGen: 15492K-&gt;840K(76288K)] 15492K-&gt;11088K(251392K), <span class="number">0.0070281</span> secs] [Times: user=<span class="number">0.08</span> sys=<span class="number">0.00</span>, real=<span class="number">0.01</span> secs] </span><br><span class="line">[<span class="function">Full <span class="title">GC</span> <span class="params">(System.gc()</span>) [PSYoungGen: 840K-&gt;0<span class="title">K</span><span class="params">(76288K)</span>] [ParOldGen: 10248K-&gt;10900<span class="title">K</span><span class="params">(175104K)</span>] 11088K-&gt;10900<span class="title">K</span><span class="params">(251392K)</span>, [Metaspace: 3386K-&gt;3386<span class="title">K</span><span class="params">(1056768K)</span>], 0.0084464 secs] [Times: user</span>=<span class="number">0.00</span> sys=<span class="number">0.00</span>, real=<span class="number">0.01</span> secs] </span><br><span class="line">Heap</span><br><span class="line"> PSYoungGen      total 76288K, used 1966K [<span class="number">0x00000000fab00000</span>, <span class="number">0x0000000100000000</span>, <span class="number">0x0000000100000000</span>)</span><br><span class="line">  eden space 65536K, <span class="number">3</span>% used [<span class="number">0x00000000fab00000</span>,<span class="number">0x00000000faceb9e0</span>,<span class="number">0x00000000feb00000</span>)</span><br><span class="line">  from space 10752K, <span class="number">0</span>% used [<span class="number">0x00000000feb00000</span>,<span class="number">0x00000000feb00000</span>,<span class="number">0x00000000ff580000</span>)</span><br><span class="line">  to   space 10752K, <span class="number">0</span>% used [<span class="number">0x00000000ff580000</span>,<span class="number">0x00000000ff580000</span>,<span class="number">0x0000000100000000</span>)</span><br><span class="line"> ParOldGen       total 175104K, used 10900K [<span class="number">0x00000000f0000000</span>, <span class="number">0x00000000fab00000</span>, <span class="number">0x00000000fab00000</span>)</span><br><span class="line">  object space 175104K, <span class="number">6</span>% used [<span class="number">0x00000000f0000000</span>,<span class="number">0x00000000f0aa52e8</span>,<span class="number">0x00000000fab00000</span>)</span><br><span class="line"> Metaspace       used 3393K, capacity 4496K, committed 4864K, reserved 1056768K</span><br><span class="line">  <span class="class"><span class="keyword">class</span> <span class="title">space</span>    <span class="title">used</span> 379<span class="title">K</span>, <span class="title">capacity</span> 388<span class="title">K</span>, <span class="title">committed</span> 512<span class="title">K</span>, <span class="title">reserved</span> 1048576<span class="title">K</span></span></span><br></pre></td></tr></table></figure>

<p><strong>原因：</strong></p>
<p>1、来看看字节码：实例方法局部变量表第一个变量肯定是 this</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_011/0002.png">

<p>2、你有没有看到，局部变量表的大小是 2。但是局部变量表里只有一个索引为0的啊？那索引为1的是哪个局部变量呢？实际上索引为1的位置是buffer在占用着，执行 System.gc() 时，栈中还有 buffer 变量指向堆中的字节数组，所以没有进行GC</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_011/0003.png">

<p>3、那么这种代码块的情况，什么时候会被GC呢？我们来看第四个方法</p>
<p><strong>4、调用 localvarGC4() 方法</strong></p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">[GC (System.gc()) [PSYoungGen: 15492K-&gt;776K(76288K)] 15492K-&gt;784K(251392K), 0.0009430 secs] [Times: user&#x3D;0.00 sys&#x3D;0.00, real&#x3D;0.00 secs] </span><br><span class="line">[Full GC (System.gc()) [PSYoungGen: 776K-&gt;0K(76288K)] [ParOldGen: 8K-&gt;646K(175104K)] 784K-&gt;646K(251392K), [Metaspace: 3485K-&gt;3485K(1056768K)], 0.0065829 secs] [Times: user&#x3D;0.02 sys&#x3D;0.00, real&#x3D;0.01 secs] </span><br><span class="line">Heap</span><br><span class="line"> PSYoungGen      total 76288K, used 1966K [0x00000000fab00000, 0x0000000100000000, 0x0000000100000000)</span><br><span class="line">  eden space 65536K, 3% used [0x00000000fab00000,0x00000000faceb9f8,0x00000000feb00000)</span><br><span class="line">  from space 10752K, 0% used [0x00000000feb00000,0x00000000feb00000,0x00000000ff580000)</span><br><span class="line">  to   space 10752K, 0% used [0x00000000ff580000,0x00000000ff580000,0x0000000100000000)</span><br><span class="line"> ParOldGen       total 175104K, used 646K [0x00000000f0000000, 0x00000000fab00000, 0x00000000fab00000)</span><br><span class="line">  object space 175104K, 0% used [0x00000000f0000000,0x00000000f00a1b88,0x00000000fab00000)</span><br><span class="line"> Metaspace       used 3498K, capacity 4498K, committed 4864K, reserved 1056768K</span><br><span class="line">  class space    used 387K, capacity 390K, committed 512K, reserved 1048576K</span><br></pre></td></tr></table></figure>

<p>Q：就多定义了一个局部变量 value ，就可以把字节数组回收了呢？</p>
<p>A：局部变量表长度为 2 ，这说明了出了代码块时，buffer 就出了其作用域范围，此时没有为 value 开启新的槽，value 变量直接占据了 buffer 变量的槽（Slot），导致堆中的字节数组没有引用再指向它，执行 System.gc() 时被回收。看，value 位于局部变量表中索引为 1 的位置。value这个局部变量把原本属于buffer的slot给占用了，这样栈上就没有buffer变量指向<code>new byte[10 * 1024 * 1024]</code>实例了。</p>
<blockquote>
<p>这点看不懂的可以看我前面的文章：虚拟机栈 –&gt; Slot的重复利用</p>
</blockquote>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_011/0004.png">



<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_011/0005.png">



<p><strong>调用 localvarGC5() 方法</strong></p>
<p>局部变量除了方法范围就是失效了，堆中的字节数组铁定被回收</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">[GC (System.gc()) [PSYoungGen: 15492K-&gt;840K(76288K)] 15492K-&gt;11088K(251392K), <span class="number">0.0070281</span> secs] [Times: user=<span class="number">0.00</span> sys=<span class="number">0.00</span>, real=<span class="number">0.01</span> secs] </span><br><span class="line">[<span class="function">Full <span class="title">GC</span> <span class="params">(System.gc()</span>) [PSYoungGen: 840K-&gt;0<span class="title">K</span><span class="params">(76288K)</span>] [ParOldGen: 10248K-&gt;10911<span class="title">K</span><span class="params">(175104K)</span>] 11088K-&gt;10911<span class="title">K</span><span class="params">(251392K)</span>, [Metaspace: 3492K-&gt;3492<span class="title">K</span><span class="params">(1056768K)</span>], 0.0082011 secs] [Times: user</span>=<span class="number">0.03</span> sys=<span class="number">0.03</span>, real=<span class="number">0.01</span> secs] </span><br><span class="line">[GC (System.gc()) [PSYoungGen: 0K-&gt;0K(76288K)] 10911K-&gt;10911K(251392K), <span class="number">0.0004440</span> secs] [Times: user=<span class="number">0.00</span> sys=<span class="number">0.00</span>, real=<span class="number">0.00</span> secs] </span><br><span class="line">[<span class="function">Full <span class="title">GC</span> <span class="params">(System.gc()</span>) [PSYoungGen: 0K-&gt;0<span class="title">K</span><span class="params">(76288K)</span>] [ParOldGen: 10911K-&gt;671<span class="title">K</span><span class="params">(175104K)</span>] 10911K-&gt;671<span class="title">K</span><span class="params">(251392K)</span>, [Metaspace: 3492K-&gt;3492<span class="title">K</span><span class="params">(1056768K)</span>], 0.0108555 secs] [Times: user</span>=<span class="number">0.08</span> sys=<span class="number">0.02</span>, real=<span class="number">0.01</span> secs] </span><br><span class="line">Heap</span><br><span class="line"> PSYoungGen      total 76288K, used 655K [<span class="number">0x00000000fab00000</span>, <span class="number">0x0000000100000000</span>, <span class="number">0x0000000100000000</span>)</span><br><span class="line">  eden space 65536K, <span class="number">1</span>% used [<span class="number">0x00000000fab00000</span>,<span class="number">0x00000000faba3ee8</span>,<span class="number">0x00000000feb00000</span>)</span><br><span class="line">  from space 10752K, <span class="number">0</span>% used [<span class="number">0x00000000ff580000</span>,<span class="number">0x00000000ff580000</span>,<span class="number">0x0000000100000000</span>)</span><br><span class="line">  to   space 10752K, <span class="number">0</span>% used [<span class="number">0x00000000feb00000</span>,<span class="number">0x00000000feb00000</span>,<span class="number">0x00000000ff580000</span>)</span><br><span class="line"> ParOldGen       total 175104K, used 671K [<span class="number">0x00000000f0000000</span>, <span class="number">0x00000000fab00000</span>, <span class="number">0x00000000fab00000</span>)</span><br><span class="line">  object space 175104K, <span class="number">0</span>% used [<span class="number">0x00000000f0000000</span>,<span class="number">0x00000000f00a7cf8</span>,<span class="number">0x00000000fab00000</span>)</span><br><span class="line"> Metaspace       used 3499K, capacity 4502K, committed 4864K, reserved 1056768K</span><br><span class="line">  <span class="class"><span class="keyword">class</span> <span class="title">space</span>    <span class="title">used</span> 387<span class="title">K</span>, <span class="title">capacity</span> 390<span class="title">K</span>, <span class="title">committed</span> 512<span class="title">K</span>, <span class="title">reserved</span> 1048576<span class="title">K</span></span></span><br></pre></td></tr></table></figure>



<h2 id="内存溢出与内存泄漏"><a href="#内存溢出与内存泄漏" class="headerlink" title="内存溢出与内存泄漏"></a>内存溢出与内存泄漏</h2><h3 id="内存溢出"><a href="#内存溢出" class="headerlink" title="内存溢出"></a>内存溢出</h3><ol>
<li> 内存溢出相对于内存泄漏来说，尽管更容易被理解，但是同样的，内存溢出也是引发程序崩溃的罪魁祸首之一。</li>
<li> 由于GC一直在发展，所有一般情况下，除非应用程序占用的内存增长速度非常快，造成垃圾回收已经跟不上内存消耗的速度，否则不太容易出现OOM的情况。</li>
<li> 大多数情况下，GC会进行各种年龄段的垃圾回收，实在不行了就放大招，来一次独占式的Full GC操作，这时候会回收大量的内存，供应用程序继续使用。</li>
<li> Javadoc中对OutofMemoryError的解释是，没有空闲内存，并且垃圾收集器也无法提供更多内存。</li>
</ol>
<p><strong>内存溢出（OOM）原因分析</strong></p>
<p>首先说没有空闲内存的情况：说明Java虚拟机的堆内存不够。原因有二：</p>
<ol>
<li>Java虚拟机的堆内存设置不够。<ul>
<li>  比如：可能存在内存泄漏问题；也很有可能就是堆的大小不合理，比如我们要处理比较可观的数据量，但是没有显式指定JVM堆大小或者指定数值偏小。我们可以通过参数-Xms 、-Xmx来调整。</li>
</ul>
</li>
<li>代码中创建了大量大对象，并且长时间不能被垃圾收集器收集（存在被引用）<ul>
<li>  对于老版本的Oracle JDK，因为永久代的大小是有限的，并且JVM对永久代垃圾回收（如，常量池回收、卸载不再需要的类型）非常不积极，所以当我们不断添加新类型的时候，永久代出现OutOfMemoryError也非常多见。尤其是在运行时存在大量动态类型生成的场合；类似intern字符串缓存占用太多空间，也会导致OOM问题。对应的异常信息，会标记出来和永久代相关：“java.lang.OutOfMemoryError:PermGen space”。</li>
<li>  随着元数据区的引入，方法区内存已经不再那么窘迫，所以相应的OOM有所改观，出现OOM，异常信息则变成了：“java.lang.OutofMemoryError:Metaspace”。直接内存不足，也会导致OOM。</li>
</ul>
</li>
</ol>
<ol>
<li>这里面隐含着一层意思是，在抛出OutofMemoryError之前，通常垃圾收集器会被触发，尽其所能去清理出空间。<ul>
<li>  例如：在引用机制分析中，涉及到JVM会去尝试<strong>回收软引用指向的对象</strong>等。</li>
<li>  在java.nio.Bits.reserveMemory()方法中，我们能清楚的看到，System.gc()会被调用，以清理空间。</li>
</ul>
</li>
<li>当然，也不是在任何情况下垃圾收集器都会被触发的<ul>
<li>  比如，我们去分配一个超大对象，类似一个超大数组超过堆的最大值，JVM可以判断出垃圾收集并不能解决这个问题，所以直接抛出OutofMemoryError。</li>
</ul>
</li>
</ol>
<h3 id="内存泄漏"><a href="#内存泄漏" class="headerlink" title="内存泄漏"></a>内存泄漏</h3><ol>
<li>也称作“存储渗漏”。严格来说，<strong>只有对象不会再被程序用到了，但是GC又不能回收他们的情况，才叫内存泄漏。</strong></li>
<li>但实际情况很多时候一些不太好的实践（或疏忽）会导致对象的生命周期变得很长甚至导致OOM，也可以叫做宽泛意义上的“内存泄漏”。</li>
<li>尽管内存泄漏并不会立刻引起程序崩溃，但是一旦发生内存泄漏，程序中的可用内存就会被逐步蚕食，直至耗尽所有内存，最终出现OutofMemory异常，导致程序崩溃。</li>
<li>注意，这里的存储空间并不是指物理内存，而是指虚拟内存大小，这个虚拟内存大小取决于磁盘交换区设定的大小。</li>
</ol>
<p><strong>内存泄露官方例子</strong></p>
<p>左边的图：Java使用可达性分析算法，最上面的数据不可达，就是需要被回收的对象。</p>
<p>右边的图：后期有一些对象不用了，按道理应该断开引用，但是存在一些链没有断开（图示中的Forgotten Reference Memory Leak），从而导致没有办法被回收。</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_011/0006.png">





<p><strong>常见例子</strong></p>
<ol>
<li>单例模式<ul>
<li>  单例的生命周期和应用程序是一样长的，所以在单例程序中，如果持有对外部对象的引用的话，那么这个外部对象是不能被回收的，则会导致内存泄漏的产生。</li>
</ul>
</li>
<li>一些提供close()的资源未关闭导致内存泄漏<ul>
<li>  数据库连接 dataSourse.getConnection()，网络连接socket和io连接必须手动close，否则是不能被回收的。</li>
</ul>
</li>
</ol>
<h2 id="Stop-the-World"><a href="#Stop-the-World" class="headerlink" title="Stop the World"></a>Stop the World</h2><ol>
<li>Stop-the-World，简称STW，指的是GC事件发生过程中，会产生应用程序的停顿。<strong>停顿产生时整个应用程序线程都会被暂停，没有任何响应</strong>，有点像卡死的感觉，这个停顿称为STW。</li>
<li>可达性分析算法中枚举根节点（GC Roots）会导致所有Java执行线程停顿，为什么需要停顿所有 Java 执行线程呢？<ul>
<li>分析工作必须在一个能确保一致性的快照中进行</li>
<li>一致性指整个分析期间整个执行系统看起来像被冻结在某个时间点上</li>
<li><strong>如果出现分析过程中对象引用关系还在不断变化，则分析结果的准确性无法保证</strong></li>
</ul>
</li>
<li>被STW中断的应用程序线程会在完成GC之后恢复，频繁中断会让用户感觉像是网速不快造成电影卡带一样，所以我们需要减少STW的发生。</li>
</ol>
<ol>
<li>STW事件和采用哪款GC无关，所有的GC都有这个事件。</li>
<li>哪怕是G1也不能完全避免Stop-the-world情况发生，只能说垃圾回收器越来越优秀，回收效率越来越高，尽可能地缩短了暂停时间。</li>
<li>STW是JVM在<strong>后台自动发起和自动完成</strong>的。在用户不可见的情况下，把用户正常的工作线程全部停掉。</li>
<li>开发中不要用System.gc() ，这会导致Stop-the-World的发生。</li>
</ol>
<h3 id="代码感受-Stop-the-World"><a href="#代码感受-Stop-the-World" class="headerlink" title="代码感受 Stop the World"></a>代码感受 Stop the World</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StopTheWorldDemo</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">WorkThread</span> <span class="keyword">extends</span> <span class="title">Thread</span> </span>&#123;</span><br><span class="line">        List&lt;<span class="keyword">byte</span>[]&gt; list = <span class="keyword">new</span> ArrayList&lt;<span class="keyword">byte</span>[]&gt;();</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">                    <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>;i &lt; <span class="number">1000</span>;i++)&#123;</span><br><span class="line">                        <span class="keyword">byte</span>[] buffer = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>];</span><br><span class="line">                        list.add(buffer);</span><br><span class="line">                    &#125;</span><br><span class="line"></span><br><span class="line">                    <span class="keyword">if</span>(list.size() &gt; <span class="number">10000</span>)&#123;</span><br><span class="line">                        list.clear();</span><br><span class="line">                        System.gc();<span class="comment">//会触发full gc，进而会出现STW事件</span></span><br><span class="line">                     </span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Exception ex) &#123;</span><br><span class="line">                ex.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">PrintThread</span> <span class="keyword">extends</span> <span class="title">Thread</span> </span>&#123;</span><br><span class="line">        <span class="keyword">public</span> <span class="keyword">final</span> <span class="keyword">long</span> startTime = System.currentTimeMillis();</span><br><span class="line"></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">                    <span class="comment">// 每秒打印时间信息</span></span><br><span class="line">                    <span class="keyword">long</span> t = System.currentTimeMillis() - startTime;</span><br><span class="line">                    System.out.println(t / <span class="number">1000</span> + <span class="string">&quot;.&quot;</span> + t % <span class="number">1000</span>);</span><br><span class="line">                    Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Exception ex) &#123;</span><br><span class="line">                ex.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        WorkThread w = <span class="keyword">new</span> WorkThread();</span><br><span class="line">        PrintThread p = <span class="keyword">new</span> PrintThread();</span><br><span class="line">        w.start();</span><br><span class="line">        p.start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<p>关闭工作线程 w ，观察输出：当前时间间隔与上次时间间隔<strong>基本</strong>是每隔1秒打印一次</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="number">0.1</span></span><br><span class="line"><span class="number">1.1</span></span><br><span class="line"><span class="number">2.2</span></span><br><span class="line"><span class="number">3.2</span></span><br><span class="line"><span class="number">4.3</span></span><br><span class="line"><span class="number">5.3</span></span><br><span class="line"><span class="number">6.3</span></span><br><span class="line"><span class="number">7.3</span></span><br><span class="line"></span><br><span class="line">Process finished with exit code -<span class="number">1</span></span><br></pre></td></tr></table></figure>



<p>开启工作线程 w ，观察打印输出：当前时间间隔与上次时间间隔相差 1.3s ，可以明显感受到 Stop the World 的存在</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="number">0.1</span></span><br><span class="line"><span class="number">1.4</span></span><br><span class="line"><span class="number">2.7</span></span><br><span class="line"><span class="number">3.8</span></span><br><span class="line"><span class="number">4.12</span></span><br><span class="line"><span class="number">5.13</span></span><br><span class="line"></span><br><span class="line">Process finished with exit code -<span class="number">1</span></span><br></pre></td></tr></table></figure>



<h2 id="垃圾回收的并行与并发"><a href="#垃圾回收的并行与并发" class="headerlink" title="垃圾回收的并行与并发"></a>垃圾回收的并行与并发</h2><h3 id="并发的概念"><a href="#并发的概念" class="headerlink" title="并发的概念"></a>并发的概念</h3><ol>
<li>在操作系统中，是指<strong>一个时间段</strong>中有几个程序都处于已启动运行到运行完毕之间，且这几个程序都是在同一个处理器上运行</li>
<li>并发不是真正意义上的“同时进行”，只是CPU把一个时间段划分成几个时间片段（时间区间），然后在这几个时间区间之间来回切换。由于CPU处理的速度非常快，只要时间间隔处理得当，即可让用户感觉是多个应用程序同时在进行</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_011/0007.png">



<h3 id="并行的概念"><a href="#并行的概念" class="headerlink" title="并行的概念"></a>并行的概念</h3><ol>
<li>当系统有一个以上CPU时，当一个CPU执行一个进程时，另一个CPU可以执行另一个进程，两个进程互不抢占CPU资源，可以<strong>同时</strong>进行，我们称之为并行（Parallel）</li>
<li>其实决定并行的因素不是CPU的数量，而是CPU的核心数量，比如一个CPU多个核也可以并行</li>
<li>适合科学计算，后台处理等弱交互场景</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_011/0008.png">

<blockquote>
<p><strong>并发与并行的对比</strong></p>
</blockquote>
<ol>
<li> 并发，指的是多个事情，在同一时间段内同时发生了。</li>
<li> 并行，指的是多个事情，在同一时间点上（或者说同一时刻）同时发生了。</li>
<li> 并发的多个任务之间是互相抢占资源的。并行的多个任务之间是不互相抢占资源的。</li>
<li> 只有在多CPU或者一个CPU多核的情况中，才会发生并行。否则，看似同时发生的事情，其实都是并发执行的。</li>
</ol>
<h3 id="垃圾回收的并发与并行"><a href="#垃圾回收的并发与并行" class="headerlink" title="垃圾回收的并发与并行"></a>垃圾回收的并发与并行</h3><ol>
<li>并行（Parallel）：指多条垃圾收集线程并行工作，但此时用户线程仍处于等待状态。<ul>
<li>  如ParNew、Parallel Scavenge、Parallel Old</li>
</ul>
</li>
<li>串行（Serial）<ul>
<li>  相较于并行的概念，单线程执行。</li>
<li>  如果内存不够，则程序暂停，启动JVM垃圾回收器进行垃圾回收（单线程）</li>
</ul>
</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_011/0009.png">



<p>并发和并行，在谈论垃圾收集器的上下文语境中，它们可以解释如下：</p>
<ol>
<li>并发（Concurrent）：指<strong>用户线程与垃圾收集线程同时执行</strong>（但不一定是并行的，可能会交替执行），垃圾回收线程在执行时不会停顿用户程序的运行。<ul>
<li>比如用户程序在继续运行，而垃圾收集程序线程运行于另一个CPU上；</li>
</ul>
</li>
<li> 典型垃圾回收器：CMS、G1</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_011/0010.png">



<h2 id="HotSpot的算法实现细节"><a href="#HotSpot的算法实现细节" class="headerlink" title="HotSpot的算法实现细节"></a>HotSpot的算法实现细节</h2><h3 id="根节点枚举"><a href="#根节点枚举" class="headerlink" title="根节点枚举"></a>根节点枚举</h3><p>1、固定可作为GC Roots的节点主要在全局性的引用（例如常量或类静态属性）与执行上下文（例如栈帧中的本地变量表）中，尽管目标明确，但查找过程要做到高效并非一件容易的事情，现在Java应用越做越庞大，光是方法区的大小就常有数百上千兆，里面的类、常量等更是恒河沙数，若要逐个检查以这里为起源的引用肯定得消耗不少时间。 </p>
<p>2、迄今为止，<strong>所有收集器在根节点枚举这一步骤时都是必须暂停用户线程的</strong>，因此毫无疑问根节点 枚举与之前提及的整理内存碎片一样会面临相似的“Stop The World”的困扰。现在可达性分析算法耗时 最长的查找引用链的过程已经可以做到与用户线程一起并发，<strong>但根节点枚举始终还 是必须在一个能保障一致性的快照中才得以进行</strong>——这里“一致性”的意思是整个枚举期间执行子系统 看起来就像被冻结在某个时间点上，不会出现分析过程中，根节点集合的对象引用关系还在不断变化 的情况，若这点不能满足的话，分析结果准确性也就无法保证。这是导致垃圾收集过程必须停顿所有 用户线程的其中一个重要原因，即使是号称停顿时间可控，或者（几乎）不会发生停顿的CMS、G1、 ZGC等收集器，枚举根节点时也是必须要停顿的。</p>
<p>3、由于目前主流Java虚拟机使用的都是<strong>准确式垃圾收集</strong>，所以当用户线程停顿下来之后，其实并不需要一个不漏地检查完所有 执行上下文和全局的引用位置，虚拟机应当是有办法直接得到哪些地方存放着对象引用的。在HotSpot 的解决方案里，是使用一组称为<strong>OopMap的数据结构</strong>来达到这个目的。一旦类加载动作完成的时候， HotSpot就会把对象内什么偏移量上是什么类型的数据计算出来，在即时编译过程中，也 会在特定的位置记录下栈里和寄存器里哪些位置是引用。这样收集器在扫描时就可以直接得知这些信 息了，<strong>并不需要真正一个不漏地从方法区等GC Roots开始查找</strong>。</p>
<p>4、Exact VM因它使用<strong>准确式内存管理</strong>（Exact Memory Management，也可以叫Non-Con- servative/Accurate Memory Management）而得名。准确式内存管理是指虚拟机可以知道内存中某个位 置的数据具体是什么类型。譬如内存中有一个32bit的整数123456，虚拟机将有能力分辨出它到底是一 个指向了123456的内存地址的引用类型还是一个数值为123456的整数，准确分辨出哪些内存是引用类 型，这也是在垃圾收集时准确判断堆上的数据是否还可能被使用的前提。【<strong>这个不是特别重要，了解一下即可</strong>】</p>
<blockquote>
<p>常考面试：<strong>在OopMap的协助下，HotSpot可以快速准确地完成GC Roots枚举</strong></p>
</blockquote>
<h3 id="安全点与安全区域"><a href="#安全点与安全区域" class="headerlink" title="安全点与安全区域"></a>安全点与安全区域</h3><p><strong>安全点（Safepoint）</strong></p>
<ol>
<li>程序执行时并非在所有地方都能停顿下来开始GC，只有在特定的位置才能停顿下来开始GC，这些位置称为“安全点（Safepoint）”。</li>
<li>Safe Point的选择很重要，<strong>如果太少可能导致GC等待的时间太长，如果太频繁可能导致运行时的性能问题</strong>。大部分指令的执行时间都非常短暂，通常会根据“<strong>是否具有让程序长时间执行的特征</strong>”为标准。比如：选择一些执行时间较长的指令作为Safe Point，<strong>如方法调用、循环跳转和异常跳转等</strong>。</li>
</ol>
<p><strong>如何在GC发生时，检查所有线程都跑到最近的安全点停顿下来呢？</strong></p>
<ol>
<li> 抢先式中断：（目前没有虚拟机采用了）首先中断所有线程。如果还有线程不在安全点，就恢复线程，让线程跑到安全点。</li>
<li> 主动式中断：设置一个中断标志，各个线程运行到Safe Point的时候<strong>主动轮询</strong>这个标志，如果中断标志为真，则将自己进行中断挂起。</li>
</ol>
<p><strong>安全区域（Safe Region）</strong></p>
<ol>
<li> Safepoint 机制保证了程序执行时，在不太长的时间内就会遇到可进入GC的Safepoint。但是，程序“不执行”的时候呢？</li>
<li> 例如线程处于Sleep状态或Blocked 状态，这时候线程无法响应JVM的中断请求，“走”到安全点去中断挂起，JVM也不太可能等待线程被唤醒。对于这种情况，就需要安全区域（Safe Region）来解决。</li>
<li> <strong>安全区域是指在一段代码片段中，对象的引用关系不会发生变化，在这个区域中的任何位置开始GC都是安全的</strong>。我们也可以把Safe Region看做是被扩展了的Safepoint。</li>
</ol>
<p><strong>安全区域的执行流程</strong></p>
<ol>
<li> 当线程运行到Safe Region的代码时，首先标识已经进入了Safe Region，如果这段时间内发生GC，JVM会忽略标识为Safe Region状态的线程</li>
<li> 当线程即将离开Safe Region时，会检查JVM是否已经完成根节点枚举（即GC Roots的枚举），如果完成了，则继续运行，否则线程必须等待直到收到可以安全离开Safe Region的信号为止；</li>
</ol>
<h3 id="记忆集与卡表"><a href="#记忆集与卡表" class="headerlink" title="记忆集与卡表"></a>记忆集与卡表</h3><h4 id="什么是跨代引用？"><a href="#什么是跨代引用？" class="headerlink" title="什么是跨代引用？"></a>什么是跨代引用？</h4><p>1、一般的垃圾回收算法至少会划分出两个年代，年轻代和老年代。但是单纯的分代理论在垃圾回收的时候存在一个巨大的缺陷：为了找到年轻代中的存活对象，却不得不遍历整个老年代，反过来也是一样的。</p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_011/0011.png">

<p>2、如果我们从年轻代开始遍历，那么可以断定N, S, P, Q都是存活对象。但是，V却不会被认为是存活对象，其占据的内存会被回收了。这就是一个惊天的大漏洞！因为U本身是老年代对象，而且有外部引用指向它，也就是说U是存活对象，而U指向了V，也就是说V也应该是存活对象才是！而这都是因为我们只遍历年轻代对象！</p>
<p>3、所以，为了解决这种跨代引用的问题，最笨的办法就是遍历老年代的对象，找出这些跨代引用来。这种方案存在极大的性能浪费。因为从两个分代假说里面，其实隐含了一个推论：跨代引用是极少的。也就是为了找出那么一点点跨代引用，我们却得遍历整个老年代！从上图来说，很显然的是，我们根本不必遍历R。</p>
<p>4、因此，为了避免这种遍历老年代的性能开销，通常的分代垃圾回收器会引入一种称为<strong>记忆集</strong>的技术。<strong>简单来说，记忆集就是用来记录跨代引用的表。</strong></p>
<h4 id="记忆集与卡表-1"><a href="#记忆集与卡表-1" class="headerlink" title="记忆集与卡表"></a>记忆集与卡表</h4><p>1、为解决对象跨代引用所带来的问题，垃圾收集器在新生代中建 立了名为<strong>记忆集（Remembered Set）的数据结构</strong>，用以避免把整个老年代加进GC Roots扫描范围。事实上并不只是新生代、老年代之间才有跨代引用的问题，所有涉及部分区域收集（Partial GC）行为的 垃圾收集器，典型的如G1、ZGC和Shenandoah收集器，都会面临相同的问题，因此我们有必要进一步 理清记忆集的原理和实现方式，以便在后续章节里介绍几款最新的收集器相关知识时能更好地理解。</p>
<p>2、记忆集是一种用于记录<strong>从非收集区域指向收集区域的指针集合的抽象数据结构</strong>。如果我们不考虑效率和成本的话，最简单的实现可以用非收集区域中所有含跨代引用的对象数组来实现这个数据结构。</p>
<blockquote>
<p>比如说我们有老年代（非收集区域）和年轻代（收集区域）的对象之间有一条引用链</p>
</blockquote>
<p>3、这种记录全部含跨代引用对象的实现方案，无论是空间占用还是维护成本都相当高昂。而在垃圾 收集的场景中，收集器只需要通过记忆集判断出某一块非收集区域是否存在有指向了收集区域的指针 就可以了，并不需要了解这些跨代指针的全部细节。那设计者在实现记忆集的时候，便可以选择更为 粗犷的记录粒度来节省记忆集的存储和维护成本，下面列举了一些可供选择（当然也可以选择这个范 围以外的）的记录精度：</p>
<ul>
<li>字长精度：每个记录精确到一个机器字长（就是处理器的寻址位数，如常见的32位或64位，这个 精度决定了机器访问物理内存地址的指针长度），该字包含跨代指针。 </li>
<li>对象精度：每个记录精确到一个对象，该对象里有字段含有跨代指针。 </li>
<li>卡精度：每个记录精确到一块内存区域，该区域内有对象含有跨代指针。</li>
</ul>
<p>4、其中，第三种“卡精度”所指的是用一种称为“卡表”（Card Table）的方式去实现记忆集，这也是 目前最常用的一种记忆集实现形式，一些资料中甚至直接把它和记忆集混为一谈。前面定义中提到记 忆集其实是一种“抽象”的数据结构，抽象的意思是只定义了记忆集的行为意图，并没有定义其行为的 具体实现。卡表就是记忆集的一种具体实现，它定义了记忆集的记录精度、与堆内存的映射关系等。 关于卡表与记忆集的关系，读者不妨按照Java语言中HashMap与Map的关系来类比理解。 卡表最简单的形式可以只是一个字节数组，而HotSpot虚拟机确实也是这样做的</p>
<blockquote>
<p>读者只需要知道有这个东西，面试的时候能说出来，再细致一点的就需要看周志明老师的第三版书了</p>
</blockquote>
<h2 id="再谈引用概述"><a href="#再谈引用概述" class="headerlink" title="再谈引用概述"></a>再谈引用概述</h2><ol>
<li>我们希望能描述这样一类对象：当内存空间还足够时，则能保留在内存中；如果内存空间在进行垃圾收集后还是很紧张，则可以抛弃这些对象。</li>
<li>既偏门又非常高频的面试题：强引用、软引用、弱引用、虚引用有什么区别？具体使用场景是什么？</li>
<li>在JDK1.2版之后，Java对引用的概念进行了扩充，将引用分为：<ul>
<li>  强引用（Strong Reference）</li>
<li>  软引用（Soft Reference）</li>
<li>  弱引用（Weak Reference）</li>
<li>  虚引用（Phantom Reference）</li>
</ul>
</li>
<li>这4种引用强度依次逐渐减弱。除强引用外，其他3种引用均可以在java.lang.ref包中找到它们的身影。如下图，显示了这3种引用类型对应的类，开发人员可以在应用程序中直接使用它们。</li>
</ol>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_011/0012.png" >



<p>Reference子类中只有终结器引用是包内可见的，其他3种引用类型均为public，可以在应用程序中直接使用</p>
<ol>
<li> 强引用（StrongReference）：最传统的“引用”的定义，是指在程序代码之中普遍存在的引用赋值，即类似“<code>object obj=new Object()</code>”这种引用关系。无论任何情况下，只要强引用关系还存在，垃圾收集器就永远不会回收掉被引用的对象。宁可报OOM，也不会GC强引用</li>
<li> 软引用（SoftReference）：在系统将要发生内存溢出之前，将会把这些对象列入回收范围之中进行第二次回收。如果这次回收后还没有足够的内存，才会抛出内存溢出异常。</li>
<li> 弱引用（WeakReference）：被弱引用关联的对象只能生存到下一次垃圾收集之前。当垃圾收集器工作时，无论内存空间是否足够，都会回收掉被弱引用关联的对象。</li>
<li> 虚引用（PhantomReference）：一个对象是否有虚引用的存在，完全不会对其生存时间构成影响，也无法通过虚引用来获得一个对象的实例。为一个对象设置虚引用关联的唯一目的就是能在这个对象被收集器回收时收到一个系统通知。</li>
</ol>
<h2 id="再谈引用：强引用"><a href="#再谈引用：强引用" class="headerlink" title="再谈引用：强引用"></a>再谈引用：强引用</h2><ol>
<li>在Java程序中，最常见的引用类型是强引用（普通系统99%以上都是强引用），也就是我们最常见的普通对象引用，<strong>也是默认的引用类型</strong>。</li>
<li>当在Java语言中使用new操作符创建一个新的对象，并将其赋值给一个变量的时候，这个变量就成为指向该对象的一个强引用。</li>
<li><strong>只要强引用的对象是可触及的，垃圾收集器就永远不会回收掉被引用的对象。</strong>只要强引用的对象是可达的，jvm宁可报OOM，也不会回收强引用。</li>
<li>对于一个普通的对象，如果没有其他的引用关系，只要超过了引用的作用域或者显式地将相应（强）引用赋值为null，就是可以当做垃圾被收集了，当然具体回收时机还是要看垃圾收集策略。</li>
<li>相对的，软引用、弱引用和虚引用的对象是软可触及、弱可触及和虚可触及的，在一定条件下，都是可以被回收的。所以，强引用是造成Java内存泄漏的主要原因之一。</li>
</ol>
<p><strong>强引用代码举例</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StrongReferenceTest</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        StringBuffer str = <span class="keyword">new</span> StringBuffer (<span class="string">&quot;Hello,尚硅谷&quot;</span>);</span><br><span class="line">        StringBuffer str1 = str;</span><br><span class="line"></span><br><span class="line">        str = <span class="keyword">null</span>;</span><br><span class="line">        System.gc();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Thread.sleep(<span class="number">3000</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        System.out.println(str1);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>输出</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Hello,尚硅谷</span><br></pre></td></tr></table></figure>



<p>局部变量str指向stringBuffer实例所在堆空间，通过str可以操作该实例，那么str就是stringBuffer实例的强引用对应内存结构：</p>
<p><code>StringBuffer str = new StringBuffer(&quot;hello,尚硅谷&quot;);</code></p>
<img src= "" data-lazy-src="https://upyunimg.imlql.cn/youthlql@1.0.8/JVM/chapter_011/0013.png">



<p><strong>总结</strong></p>
<p>本例中的两个引用，都是强引用，强引用具备以下特点：</p>
<ol>
<li> 强引用可以直接访问目标对象。</li>
<li> 强引用所指向的对象在任何时候都不会被系统回收，虚拟机宁愿抛出OOM异常，也不会回收强引用所指向对象。</li>
<li> 强引用可能导致内存泄漏。</li>
</ol>
<h2 id="再谈引用：软引用"><a href="#再谈引用：软引用" class="headerlink" title="再谈引用：软引用"></a>再谈引用：软引用</h2><p><strong>软引用（Soft Reference）：内存不足即回收</strong></p>
<ol>
<li>软引用是用来描述一些还有用，但非必需的对象。只被软引用关联着的对象，在系统将要发生内存溢出异常前，会把这些对象列进回收范围之中进行第二次回收，如果这次回收还没有足够的内存，才会抛出内存溢出异常。注意，这里的第一次回收是不可达的对象</li>
<li>软引用通常用来实现内存敏感的缓存。比如：高速缓存就有用到软引用。如果还有空闲内存，就可以暂时保留缓存，当内存不足时清理掉，这样就保证了使用缓存的同时，不会耗尽内存。</li>
<li>垃圾回收器在某个时刻决定回收软可达的对象的时候，会清理软引用，并可选地把引用存放到一个引用队列（Reference Queue）。</li>
<li>类似弱引用，只不过Java虚拟机会尽量让软引用的存活时间长一些，迫不得已才清理。</li>
<li>一句话概括：当内存足够时，不会回收软引用可达的对象。内存不够时，会回收软引用的可达对象</li>
</ol>
<p>在JDK1.2版之后提供了SoftReference类来实现软引用</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">Object obj = <span class="keyword">new</span> Object();<span class="comment">// 声明强引用</span></span><br><span class="line">SoftReference&lt;Object&gt; sf = <span class="keyword">new</span> SoftReference&lt;&gt;(obj);</span><br><span class="line">obj = <span class="keyword">null</span>; <span class="comment">//销毁强引用</span></span><br></pre></td></tr></table></figure>



<p><strong>软引用代码举例</strong></p>
<p>代码</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SoftReferenceTest</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">User</span><span class="params">(<span class="keyword">int</span> id, String name)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.id = id;</span><br><span class="line">            <span class="keyword">this</span>.name = name;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">public</span> <span class="keyword">int</span> id;</span><br><span class="line">        <span class="keyword">public</span> String name;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="string">&quot;[id=&quot;</span> + id + <span class="string">&quot;, name=&quot;</span> + name + <span class="string">&quot;] &quot;</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//创建对象，建立软引用</span></span><br><span class="line"><span class="comment">//        SoftReference&lt;User&gt; userSoftRef = new SoftReference&lt;User&gt;(new User(1, &quot;songhk&quot;));</span></span><br><span class="line">        <span class="comment">//上面的一行代码，等价于如下的三行代码</span></span><br><span class="line">        User u1 = <span class="keyword">new</span> User(<span class="number">1</span>,<span class="string">&quot;songhk&quot;</span>);</span><br><span class="line">        SoftReference&lt;User&gt; userSoftRef = <span class="keyword">new</span> SoftReference&lt;User&gt;(u1);</span><br><span class="line">        u1 = <span class="keyword">null</span>;<span class="comment">//取消强引用</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">//从软引用中重新获得强引用对象</span></span><br><span class="line">        System.out.println(userSoftRef.get());</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;---目前内存还不紧张---&quot;</span>);</span><br><span class="line">        System.gc();</span><br><span class="line">        System.out.println(<span class="string">&quot;After GC:&quot;</span>);</span><br><span class="line"><span class="comment">//        //垃圾回收之后获得软引用中的对象</span></span><br><span class="line">        System.out.println(userSoftRef.get());<span class="comment">//由于堆空间内存足够，所有不会回收软引用的可达对象。</span></span><br><span class="line">        System.out.println(<span class="string">&quot;---下面开始内存紧张了---&quot;</span>);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//让系统认为内存资源紧张、不够</span></span><br><span class="line"><span class="comment">//            byte[] b = new byte[1024 * 1024 * 7];</span></span><br><span class="line">            <span class="keyword">byte</span>[] b = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span> * <span class="number">7168</span> - <span class="number">635</span> * <span class="number">1024</span>];</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="comment">//再次从软引用中获取数据</span></span><br><span class="line">            System.out.println(userSoftRef.get());<span class="comment">//在报OOM之前，垃圾回收器会回收软引用的可达对象。</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>JVM参数</p>
<p><code>-Xms10m -Xmx10m</code></p>
<p>在 JVM 内存不足时，会清理软引用对象</p>
<p>输出结果：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">[id=<span class="number">1</span>, name=songhk] </span><br><span class="line">---目前内存还不紧张---</span><br><span class="line">After GC:</span><br><span class="line">[id=<span class="number">1</span>, name=songhk] </span><br><span class="line">---下面开始内存紧张了---</span><br><span class="line"><span class="keyword">null</span></span><br><span class="line">java.lang.OutOfMemoryError: Java heap space</span><br><span class="line">	at com.atguigu.java1.SoftReferenceTest.main(SoftReferenceTest.java:<span class="number">48</span>)</span><br><span class="line"></span><br><span class="line">Process finished with exit code <span class="number">0</span></span><br></pre></td></tr></table></figure>





<h2 id="再谈引用：弱引用"><a href="#再谈引用：弱引用" class="headerlink" title="再谈引用：弱引用"></a>再谈引用：弱引用</h2><blockquote>
<p><strong>弱引用（Weak Reference）发现即回收</strong></p>
</blockquote>
<ol>
<li><p>弱引用也是用来描述那些非必需对象，<strong>只被弱引用关联的对象只能生存到下一次垃圾收集发生为止。在系统GC时，只要发现弱引用，不管系统堆空间使用是否充足，都会回收掉只被弱引用关联的对象</strong>。</p>
</li>
<li><p>但是，由于垃圾回收器的线程通常优先级很低，因此，并不一定能很快地发现持有弱引用的对象。在这种情况下，弱引用对象可以存在较长的时间。</p>
</li>
<li><p>弱引用和软引用一样，在构造弱引用时，也可以指定一个引用队列，当弱引用对象被回收时，就会加入指定的引用队列，通过这个队列可以跟踪对象的回收情况。</p>
</li>
<li><p>软引用、弱引用都非常适合来保存那些可有可无的缓存数据。如果这么做，当系统内存不足时，这些缓存数据会被回收，不会导致内存溢出。而当内存资源充足时，这些缓存数据又可以存在相当长的时间，从而起到加速系统的作用。</p>
</li>
</ol>
<p>在JDK1.2版之后提供了WeakReference类来实现弱引用</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 声明强引用</span></span><br><span class="line">Object obj = <span class="keyword">new</span> Object();</span><br><span class="line">WeakReference&lt;Object&gt; sf = <span class="keyword">new</span> WeakReference&lt;&gt;(obj);</span><br><span class="line">obj = <span class="keyword">null</span>; <span class="comment">//销毁强引用</span></span><br></pre></td></tr></table></figure>

<p>弱引用对象与软引用对象的最大不同就在于，当GC在进行回收时，需要通过算法检查是否回收软引用对象，而对于弱引用对象，GC总是进行回收。弱引用对象更容易、更快被GC回收。</p>
<p><strong>面试题：你开发中使用过WeakHashMap吗？</strong></p>
<p><strong>弱引用代码举例</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">WeakReferenceTest</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">User</span> </span>&#123;</span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="title">User</span><span class="params">(<span class="keyword">int</span> id, String name)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">this</span>.id = id;</span><br><span class="line">            <span class="keyword">this</span>.name = name;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">public</span> <span class="keyword">int</span> id;</span><br><span class="line">        <span class="keyword">public</span> String name;</span><br><span class="line"></span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> String <span class="title">toString</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="string">&quot;[id=&quot;</span> + id + <span class="string">&quot;, name=&quot;</span> + name + <span class="string">&quot;] &quot;</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        <span class="comment">//构造了弱引用</span></span><br><span class="line">        WeakReference&lt;User&gt; userWeakRef = <span class="keyword">new</span> WeakReference&lt;User&gt;(<span class="keyword">new</span> User(<span class="number">1</span>, <span class="string">&quot;songhk&quot;</span>));</span><br><span class="line">        <span class="comment">//从弱引用中重新获取对象</span></span><br><span class="line">        System.out.println(userWeakRef.get());</span><br><span class="line"></span><br><span class="line">        System.gc();</span><br><span class="line">        <span class="comment">// 不管当前内存空间足够与否，都会回收它的内存</span></span><br><span class="line">        System.out.println(<span class="string">&quot;After GC:&quot;</span>);</span><br><span class="line">        <span class="comment">//重新尝试从弱引用中获取对象</span></span><br><span class="line">        System.out.println(userWeakRef.get());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<p>执行垃圾回收后，软引用对象必定被清除</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">[id=<span class="number">1</span>, name=songhk] </span><br><span class="line">After GC:</span><br><span class="line"><span class="keyword">null</span></span><br><span class="line"></span><br><span class="line">Process finished with exit code <span class="number">0</span></span><br></pre></td></tr></table></figure>



<h2 id="再谈引用：虚引用"><a href="#再谈引用：虚引用" class="headerlink" title="再谈引用：虚引用"></a>再谈引用：虚引用</h2><p><strong>虚引用（Phantom Reference）：对象回收跟踪</strong></p>
<ol>
<li>也称为“幽灵引用”或者“幻影引用”，是所有引用类型中最弱的一个</li>
<li>一个对象是否有虚引用的存在，完全不会决定对象的生命周期。如果一个对象仅持有虚引用，那么它和没有引用几乎是一样的，随时都可能被垃圾回收器回收。</li>
<li>它不能单独使用，也无法通过虚引用来获取被引用的对象。当试图通过虚引用的get()方法取得对象时，总是null 。<strong>即通过虚引用无法获取到我们的数据</strong></li>
<li><strong>为一个对象设置虚引用关联的唯一目的在于跟踪垃圾回收过程。比如：能在这个对象被收集器回收时收到一个系统通知。</strong></li>
<li>虚引用必须和引用队列一起使用。虚引用在创建时必须提供一个引用队列作为参数。当垃圾回收器准备回收一个对象时，如果发现它还有虚引用，就会在回收对象后，将这个虚引用加入引用队列，以通知应用程序对象的回收情况。</li>
<li>由于虚引用可以跟踪对象的回收时间，因此，也可以将一些资源释放操作放置在虚引用中执行和记录。</li>
</ol>
<p>在JDK1.2版之后提供了PhantomReference类来实现虚引用。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 声明强引用</span></span><br><span class="line">Object obj = <span class="keyword">new</span> Object();</span><br><span class="line"><span class="comment">// 声明引用队列</span></span><br><span class="line">ReferenceQueue phantomQueue = <span class="keyword">new</span> ReferenceQueue();</span><br><span class="line"><span class="comment">// 声明虚引用（还需要传入引用队列）</span></span><br><span class="line">PhantomReference&lt;Object&gt; sf = <span class="keyword">new</span> PhantomReference&lt;&gt;(obj, phantomQueue);</span><br><span class="line">obj = <span class="keyword">null</span>; </span><br></pre></td></tr></table></figure>



<p><strong>虚引用代码示例</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PhantomReferenceTest</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> PhantomReferenceTest obj;<span class="comment">//当前类对象的声明</span></span><br><span class="line">    <span class="keyword">static</span> ReferenceQueue&lt;PhantomReferenceTest&gt; phantomQueue = <span class="keyword">null</span>;<span class="comment">//引用队列</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="class"><span class="keyword">class</span> <span class="title">CheckRefQueue</span> <span class="keyword">extends</span> <span class="title">Thread</span> </span>&#123;</span><br><span class="line">        <span class="meta">@Override</span></span><br><span class="line">        <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">            <span class="keyword">while</span> (<span class="keyword">true</span>) &#123;</span><br><span class="line">                <span class="keyword">if</span> (phantomQueue != <span class="keyword">null</span>) &#123;</span><br><span class="line">                    PhantomReference&lt;PhantomReferenceTest&gt; objt = <span class="keyword">null</span>;</span><br><span class="line">                    <span class="keyword">try</span> &#123;</span><br><span class="line">                        objt = (PhantomReference&lt;PhantomReferenceTest&gt;) phantomQueue.remove();</span><br><span class="line">                    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                        e.printStackTrace();</span><br><span class="line">                    &#125;</span><br><span class="line">                    <span class="keyword">if</span> (objt != <span class="keyword">null</span>) &#123;</span><br><span class="line">                        System.out.println(<span class="string">&quot;追踪垃圾回收过程：PhantomReferenceTest实例被GC了&quot;</span>);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">finalize</span><span class="params">()</span> <span class="keyword">throws</span> Throwable </span>&#123; <span class="comment">//finalize()方法只能被调用一次！</span></span><br><span class="line">        <span class="keyword">super</span>.finalize();</span><br><span class="line">        System.out.println(<span class="string">&quot;调用当前类的finalize()方法&quot;</span>);</span><br><span class="line">        obj = <span class="keyword">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Thread t = <span class="keyword">new</span> CheckRefQueue();</span><br><span class="line">        t.setDaemon(<span class="keyword">true</span>);<span class="comment">//设置为守护线程：当程序中没有非守护线程时，守护线程也就执行结束。</span></span><br><span class="line">        t.start();</span><br><span class="line"></span><br><span class="line">        phantomQueue = <span class="keyword">new</span> ReferenceQueue&lt;PhantomReferenceTest&gt;();</span><br><span class="line">        obj = <span class="keyword">new</span> PhantomReferenceTest();</span><br><span class="line">        <span class="comment">//构造了 PhantomReferenceTest 对象的虚引用，并指定了引用队列</span></span><br><span class="line">        PhantomReference&lt;PhantomReferenceTest&gt; phantomRef = <span class="keyword">new</span> PhantomReference&lt;PhantomReferenceTest&gt;(obj, phantomQueue);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//不可获取虚引用中的对象</span></span><br><span class="line">            System.out.println(phantomRef.get());</span><br><span class="line">			System.out.println(<span class="string">&quot;第 1 次 gc&quot;</span>);</span><br><span class="line">            <span class="comment">//将强引用去除</span></span><br><span class="line">            obj = <span class="keyword">null</span>;</span><br><span class="line">            <span class="comment">//第一次进行GC,由于对象可复活，GC无法回收该对象</span></span><br><span class="line">            System.gc();</span><br><span class="line">            Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">            <span class="keyword">if</span> (obj == <span class="keyword">null</span>) &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;obj 是 null&quot;</span>);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;obj 可用&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println(<span class="string">&quot;第 2 次 gc&quot;</span>);</span><br><span class="line">            obj = <span class="keyword">null</span>;</span><br><span class="line">            System.gc(); <span class="comment">//一旦将obj对象回收，就会将此虚引用存放到引用队列中。</span></span><br><span class="line">            Thread.sleep(<span class="number">1000</span>);</span><br><span class="line">            <span class="keyword">if</span> (obj == <span class="keyword">null</span>) &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;obj 是 null&quot;</span>);</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                System.out.println(<span class="string">&quot;obj 可用&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p>1、第一次尝试获取虚引用的值，发现无法获取的，这是因为虚引用是无法直接获取对象的值，然后进行第一次GC，因为会调用finalize方法，将对象复活了，所以对象没有被回收</p>
<p>2、但是调用第二次GC操作的时候，因为finalize方法只能执行一次，所以就触发了GC操作，将对象回收了，同时将会触发第二个操作就是将待回收的对象存入到引用队列中。</p>
<p>输出结果：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">null</span></span><br><span class="line">第 <span class="number">1</span> 次 gc</span><br><span class="line">调用当前类的finalize()方法</span><br><span class="line">obj 可用</span><br><span class="line">第 <span class="number">2</span> 次 gc</span><br><span class="line">追踪垃圾回收过程：PhantomReferenceTest实例被GC了</span><br><span class="line">obj 是 <span class="keyword">null</span></span><br><span class="line"></span><br><span class="line">Process finished with exit code <span class="number">0</span></span><br></pre></td></tr></table></figure>



<h2 id="再谈引用：终结器引用（了解）"><a href="#再谈引用：终结器引用（了解）" class="headerlink" title="再谈引用：终结器引用（了解）"></a>再谈引用：终结器引用（了解）</h2><ol>
<li>它用于实现对象的finalize() 方法，也可以称为终结器引用</li>
<li>无需手动编码，其内部配合引用队列使用</li>
<li> 在GC时，终结器引用入队。由Finalizer线程通过终结器引用找到被引用对象调用它的finalize()方法，第二次GC时才回收被引用的对象</li>
</ol>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">youthlql</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://imlql.cn/post/4d401a8b.html">https://imlql.cn/post/4d401a8b.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://imlql.cn" target="_blank">风祈的时光录</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/JVM/">JVM</a><a class="post-meta__tags" href="/tags/%E8%99%9A%E6%8B%9F%E6%9C%BA/">虚拟机</a></div><div class="post_share"></div></div><div class="post-reward"><div class="reward-button"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="https://npm.elemecdn.com/youthlql@1.0.8/blog/wechat.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://npm.elemecdn.com/youthlql@1.0.8/blog/wechat.jpg" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="https://npm.elemecdn.com/youthlql@1.0.8/blog/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="https://npm.elemecdn.com/youthlql@1.0.8/blog/alipay.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/post/7706d61d.html"><img class="prev-cover" src= "" data-lazy-src="https://upyunimg.imlql.cn/lql_static@latest/logo/jvm.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">JVM系列-第12章-垃圾回收器</div></div></a></div><div class="next-post pull-right"><a href="/post/d54daa0f.html"><img class="next-cover" src= "" data-lazy-src="https://upyunimg.imlql.cn/lql_static@latest/logo/jvm.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">JVM系列-第10章-垃圾回收概述和相关算法</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/post/debff71a.html" title="JVM系列-第7章-对象的实例化内存布局与访问定位"><img class="cover" src= "" data-lazy-src="https://upyunimg.imlql.cn/lql_static@latest/logo/jvm.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-11-14</div><div class="title">JVM系列-第7章-对象的实例化内存布局与访问定位</div></div></a></div><div><a href="/post/8c954c6.html" title="JVM系列-第1章-JVM与Java体系结构"><img class="cover" src= "" data-lazy-src="https://upyunimg.imlql.cn/lql_static@latest/logo/jvm.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-11-02</div><div class="title">JVM系列-第1章-JVM与Java体系结构</div></div></a></div><div><a href="/post/2e0079af.html" title="JVM系列-第2章-类加载子系统"><img class="cover" src= "" data-lazy-src="https://upyunimg.imlql.cn/lql_static@latest/logo/jvm.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-11-02</div><div class="title">JVM系列-第2章-类加载子系统</div></div></a></div><div><a href="/post/a7ad3cab.html" title="JVM系列-第3章-运行时数据区"><img class="cover" src= "" data-lazy-src="https://upyunimg.imlql.cn/lql_static@latest/logo/jvm.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-11-09</div><div class="title">JVM系列-第3章-运行时数据区</div></div></a></div><div><a href="/post/408712f4.html" title="JVM系列-第8章-执行引擎"><img class="cover" src= "" data-lazy-src="https://upyunimg.imlql.cn/lql_static@latest/logo/jvm.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-11-15</div><div class="title">JVM系列-第8章-执行引擎</div></div></a></div><div><a href="/post/d54daa0f.html" title="JVM系列-第10章-垃圾回收概述和相关算法"><img class="cover" src= "" data-lazy-src="https://upyunimg.imlql.cn/lql_static@latest/logo/jvm.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-11-16</div><div class="title">JVM系列-第10章-垃圾回收概述和相关算法</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content is-expand"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E7%9B%B8%E5%85%B3%E6%A6%82%E5%BF%B5"><span class="toc-text">垃圾回收相关概念</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#System-gc-%E7%9A%84%E7%90%86%E8%A7%A3"><span class="toc-text">System.gc() 的理解</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%89%8B%E5%8A%A8-GC-%E7%90%86%E8%A7%A3%E4%B8%8D%E5%8F%AF%E8%BE%BE%E5%AF%B9%E8%B1%A1%E7%9A%84%E5%9B%9E%E6%94%B6%E8%A1%8C%E4%B8%BA"><span class="toc-text">手动 GC 理解不可达对象的回收行为</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%86%85%E5%AD%98%E6%BA%A2%E5%87%BA%E4%B8%8E%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F"><span class="toc-text">内存溢出与内存泄漏</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%86%85%E5%AD%98%E6%BA%A2%E5%87%BA"><span class="toc-text">内存溢出</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F"><span class="toc-text">内存泄漏</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Stop-the-World"><span class="toc-text">Stop the World</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E6%84%9F%E5%8F%97-Stop-the-World"><span class="toc-text">代码感受 Stop the World</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E7%9A%84%E5%B9%B6%E8%A1%8C%E4%B8%8E%E5%B9%B6%E5%8F%91"><span class="toc-text">垃圾回收的并行与并发</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B9%B6%E5%8F%91%E7%9A%84%E6%A6%82%E5%BF%B5"><span class="toc-text">并发的概念</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%B9%B6%E8%A1%8C%E7%9A%84%E6%A6%82%E5%BF%B5"><span class="toc-text">并行的概念</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E7%9A%84%E5%B9%B6%E5%8F%91%E4%B8%8E%E5%B9%B6%E8%A1%8C"><span class="toc-text">垃圾回收的并发与并行</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#HotSpot%E7%9A%84%E7%AE%97%E6%B3%95%E5%AE%9E%E7%8E%B0%E7%BB%86%E8%8A%82"><span class="toc-text">HotSpot的算法实现细节</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A0%B9%E8%8A%82%E7%82%B9%E6%9E%9A%E4%B8%BE"><span class="toc-text">根节点枚举</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AE%89%E5%85%A8%E7%82%B9%E4%B8%8E%E5%AE%89%E5%85%A8%E5%8C%BA%E5%9F%9F"><span class="toc-text">安全点与安全区域</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AE%B0%E5%BF%86%E9%9B%86%E4%B8%8E%E5%8D%A1%E8%A1%A8"><span class="toc-text">记忆集与卡表</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E8%B7%A8%E4%BB%A3%E5%BC%95%E7%94%A8%EF%BC%9F"><span class="toc-text">什么是跨代引用？</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%AE%B0%E5%BF%86%E9%9B%86%E4%B8%8E%E5%8D%A1%E8%A1%A8-1"><span class="toc-text">记忆集与卡表</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%86%8D%E8%B0%88%E5%BC%95%E7%94%A8%E6%A6%82%E8%BF%B0"><span class="toc-text">再谈引用概述</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%86%8D%E8%B0%88%E5%BC%95%E7%94%A8%EF%BC%9A%E5%BC%BA%E5%BC%95%E7%94%A8"><span class="toc-text">再谈引用：强引用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%86%8D%E8%B0%88%E5%BC%95%E7%94%A8%EF%BC%9A%E8%BD%AF%E5%BC%95%E7%94%A8"><span class="toc-text">再谈引用：软引用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%86%8D%E8%B0%88%E5%BC%95%E7%94%A8%EF%BC%9A%E5%BC%B1%E5%BC%95%E7%94%A8"><span class="toc-text">再谈引用：弱引用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%86%8D%E8%B0%88%E5%BC%95%E7%94%A8%EF%BC%9A%E8%99%9A%E5%BC%95%E7%94%A8"><span class="toc-text">再谈引用：虚引用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%86%8D%E8%B0%88%E5%BC%95%E7%94%A8%EF%BC%9A%E7%BB%88%E7%BB%93%E5%99%A8%E5%BC%95%E7%94%A8%EF%BC%88%E4%BA%86%E8%A7%A3%EF%BC%89"><span class="toc-text">再谈引用：终结器引用（了解）</span></a></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By youthlql</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text"><a href="https://www.upyun.com/?utm_source=lianmeng&utm_medium=referral" target="_blank" rel="noopener" class="one-pan-link-mark"><img style="position:relative;top:-3px; " src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/upyun/logo.png" align="absmiddle" width="60px" height="30px"></a><a target="_blank" rel="noopener" href="https://beian.miit.gov.cn"><img class="icp-icon" src= "" data-lazy-src="https://npm.elemecdn.com/lql_static@latest/logo/icp.png"><span>鄂ICP备19028890号</span></a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">简</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">本地搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://npm.elemecdn.com/@fancyapps/ui/dist/fancybox.umd.js"></script><script src="https://npm.elemecdn.com/instant.page/instantpage.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/js/search/local-search.js"></script><div class="js-pjax"></div><script defer src="https://npm.elemecdn.com/jquery@latest/dist/jquery.min.js"></script></div></body></html>